<script setup lang="ts">
import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import { itemAdd, itemInfo, itemUpdate } from '#/api/register/bus/item';
import { addressCodeMapToArray } from '#/utils/address';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { modalSchema } from './data';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    labelWidth: 110,
  },
  schema: modalSchema(),
  showDefaultActions: false,
  fieldMappingTime: [
    [
      'startAddressMap',
      [
        'startCountryCode',
        'startProvinceCode',
        'startCityCode',
        'startDistrictCode',
      ],
      null,
    ],
    [
      'returnAddressMap',
      [
        'returnCountryCode',
        'returnProvinceCode',
        'returnCityCode',
        'returnDistrictCode',
      ],
      null,
    ],
  ],
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicModal, modalApi] = useVbenModal({
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { id, copy, taskGroupId, busId } = modalApi.getData() as {
      busId?: number | string;
      copy?: boolean;
      id?: number | string;
      taskGroupId?: number | string;
    };
    isUpdate.value = !!id && !copy;
    await formApi.setValues({ busId });

    // 通过团体id查询成员列表
    formApi.updateSchema([
      {
        fieldName: 'registerId',
        componentProps: {
          groupId: taskGroupId,
        },
      },
    ]);

    if (isUpdate.value && id) {
      const record = await itemInfo(id);
      // 转成地址级联组件接收的数据格式
      addressCodeMapToArray(record, 'startAddressMap', {
        countryCodeKey: 'startCountryCode',
        provinceCodeKey: 'startProvinceCode',
        cityCodeKey: 'startCityCode',
        districtCodeKey: 'startDistrictCode',
      });
      addressCodeMapToArray(record, 'returnAddressMap', {
        countryCodeKey: 'returnCountryCode',
        provinceCodeKey: 'returnProvinceCode',
        cityCodeKey: 'returnCityCode',
        districtCodeKey: 'returnDistrictCode',
      });
      await formApi.setValues(record);
    }

    if (copy) {
      // 复制
      const copyRecord = await itemInfo(id as never);
      // 转成地址级联组件接收的数据格式
      addressCodeMapToArray(copyRecord, 'startAddressMap', {
        countryCodeKey: 'startCountryCode',
        provinceCodeKey: 'startProvinceCode',
        cityCodeKey: 'startCityCode',
        districtCodeKey: 'startDistrictCode',
      });
      addressCodeMapToArray(copyRecord, 'returnAddressMap', {
        countryCodeKey: 'returnCountryCode',
        provinceCodeKey: 'returnProvinceCode',
        cityCodeKey: 'returnCityCode',
        districtCodeKey: 'returnDistrictCode',
      });
      const {
        startAddressMap,
        startAddress,
        startTime,
        returnAddressMap,
        returnAddress,
        returnTime,
      } = copyRecord;
      console.log('copyRecord', copyRecord);
      await formApi.setValues({
        startAddressMap,
        startAddress,
        startTime,
        returnAddressMap,
        returnAddress,
        returnTime,
      });
    }
    await markInitialized();

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const data = cloneDeep(await formApi.getValues());
    await (isUpdate.value ? itemUpdate(data) : itemAdd(data));
    // console.log(data);
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <BasicModal :title="title" class="w-[550px]">
    <BasicForm />
  </BasicModal>
</template>
